import { useChatDataStore } from "@/store";
import { chatCache, saveSession } from "@/utils";
import type { ElInput } from "element-plus";

// 处理会话管理
export function useChatSession() {
  const chatDataStore = useChatDataStore();
  const textareaRef = ref<ComponentPublicInstance<typeof ElInput> | null>(null);
  // 聊天输入框内容
  const chatInput = ref("");
  // 新建会话
  const newSession = () => {
    if (chatDataStore.chatHistoryWin.length === 0) {
      return ElMessage({
        showClose: true,
        message: "已有新对话",
        type: "error",
        plain: true,
      });
    }
    chatDataStore.chatHistoryWin = [];
    chatDataStore.currentSession = undefined;
    chatDataStore.generatingMessageId = null;
    chatDataStore.currentChatId = null;
    chatInput.value = "";
  };

  const saveCurrentSession = async () => {
    const targetCategory = chatDataStore.categorizedChats.find((item) =>
      item.thisChats.some((msg) => msg.id === chatDataStore.currentChatId)
    );
    if (targetCategory?.thisChats[0]) {
      targetCategory.thisChats[0].chatHistory = [
        ...chatDataStore.chatHistoryWin,
      ];
      chatCache.set(
        targetCategory.thisChats[0].id,
        targetCategory.thisChats[0]
      );
      await saveSession(targetCategory.thisChats[0]);
    }
  };

  return {
    chatInput,
    textareaRef,
    newSession,
    saveCurrentSession,
  };
}
